package me.khrystal.rxnews.utils;

import rx.Observable;
import rx.subjects.PublishSubject;
import rx.subjects.SerializedSubject;
import rx.subjects.Subject;

/**
 * usage: use like eventbus
 * 注册并观察事件:
 * rxSubscription = RxBus.getDefault().toObserverable(Something.class).subscribe(
 * new Action1<Something>() {
 *       @Override
 *       public void call(Something sth) {
 *
 *       }
 *   },
 * new Action1<Throwable>() {
 *   @Override
 *   public void call(Throwable throwable) {
 *
 *   }
 * });
 *
 * 取消注册
 * if(!rxSubscription.isUnsubscribed()) {
 *   rxSubscription.unsubscribe();
 * }
 *
 *
 *
 * author: kHRYSTAL
 * create time: 16/6/14
 * update time:
 * email: 723526676@qq.com
 */
public class RxBusDefault {

    private static volatile RxBusDefault defaultInstance;
    private final Subject bus;

    public RxBusDefault() {
        bus = new SerializedSubject<>(PublishSubject.create());
    }

    public static RxBusDefault getDefault() {
        RxBusDefault rxBus = defaultInstance;
        if (defaultInstance == null) {
            synchronized (RxBusDefault.class) {
                rxBus = defaultInstance;
                if (defaultInstance == null) {
                    rxBus = new RxBusDefault();
                    defaultInstance = rxBus;
                }
            }
        }
        return rxBus;
    }

    public void post (Object o) {
        bus.onNext(o);
    }

    public <T> Observable<T> toObserverable (Class<T> eventType) {
        return bus.ofType(eventType);
    }
}
